package com.bei_en.teacher.admin.controller.users;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bei_en.teacher.admin.CreateMD5;
import com.bei_en.teacher.admin.model.consultation.condition.ConsultationCollectionCondition;
import com.bei_en.teacher.admin.model.education.vo.EducationVo;
import com.bei_en.teacher.admin.model.forecast.condition.ForecastCondition;
import com.bei_en.teacher.admin.model.forecast.vo.ForecastVo;
import com.bei_en.teacher.admin.model.learn.condition.LearnReportCondition;
import com.bei_en.teacher.admin.model.questions.condition.QuestionsCollectionCondition;
import com.bei_en.teacher.admin.model.questions.vo.QuestionsCollectionVo;
import com.bei_en.teacher.admin.model.regions.condition.RegionsCondition;
import com.bei_en.teacher.admin.model.regions.vo.RegionsVo;
import com.bei_en.teacher.admin.model.subject.vo.SubjectVo;
import com.bei_en.teacher.admin.model.user.condition.UserFinanceCondition;
import com.bei_en.teacher.admin.model.user.vo.UserFinanceVo;
import com.bei_en.teacher.admin.model.users.bean.Users;
import com.bei_en.teacher.admin.model.users.condition.EditPasswordUsersCondition;
import com.bei_en.teacher.admin.model.users.condition.EditPhone2UsersCondition;
import com.bei_en.teacher.admin.model.users.condition.EditPhoneUsersCondition;
import com.bei_en.teacher.admin.model.users.condition.LoginUsersCondition;
import com.bei_en.teacher.admin.model.users.condition.MyCarNumCondition;
import com.bei_en.teacher.admin.model.users.condition.RegistersUsersCondition;
import com.bei_en.teacher.admin.model.users.condition.UsersCondition;
import com.bei_en.teacher.admin.model.users.condition.UsersDetailsCondition;
import com.bei_en.teacher.admin.model.users.vo.UsersDetailsVo;
import com.bei_en.teacher.admin.model.users.vo.UsersVo;
import com.bei_en.teacher.admin.other.Consts;
import com.bei_en.teacher.admin.service.consultation.ConsultationCollectionService;
import com.bei_en.teacher.admin.service.education.EducationService;
import com.bei_en.teacher.admin.service.forecast.ForecastService;
import com.bei_en.teacher.admin.service.learn.LearnReportService;
import com.bei_en.teacher.admin.service.questions.QuestionsCollectionService;
import com.bei_en.teacher.admin.service.regions.RegionsService;
import com.bei_en.teacher.admin.service.subject.SubjectService;
import com.bei_en.teacher.admin.service.user.UserFinanceService;
import com.bei_en.teacher.admin.service.users.UsersDetailsService;
import com.bei_en.teacher.admin.service.users.UsersService;
import com.bei_en.teacher.admin.controller.BaseController;
import com.bei_en.teacher.admin.controller.regions.RegionsAPPController;
import com.bei_en.common.util.OSS.UploadUtil;
import com.bei_en.common.util.SMS.ali.SMS;
import com.bei_en.common.util.SMS.dianxin.util.RandomUtil;
import com.bei_en.common.util.interceptor.OAuthRequired;
import com.bei_en.common.web.JsonFailResult;
import com.bei_en.common.web.JsonResult;
import com.bei_en.common.web.JsonSuccessResult;
import com.bei_en.common.web.MySessionContext;
import com.google.gson.JsonObject;
import com.mysql.fabric.xmlrpc.base.Array;
import com.taobao.api.ApiException;

/**
 * 账户
 * 
 * @author Guocg
 * @date 2016-7-27 9:42:17 学段、学科
 */
@Controller
@RequestMapping("/api/Users")
public class UsersAPPController extends BaseController {
	@Autowired
	UsersDetailsService usersDetailsService;
	public static final int SECOND_TIME = 60;// 验证码发送间隔,秒
	public static final int EXPIRE_TIME = 7200;// 验证码过期时间,秒
	private static String bucketName = "jiaoshi";
	private static String img_endpoint = "oss-cn-hangzhou.aliyuncs.com";// 图片服务
	private Map<String, Date> sendCodeMap = new ConcurrentHashMap<String, Date>();// no
	@Autowired
	UsersService usersService;
	@Autowired
	RegionsService regionsService;
	@Autowired
	UserFinanceService userFinanceService;
	@Autowired
	SubjectService subjectService;
	@Autowired
	EducationService educationService;
	@Autowired
	ConsultationCollectionService consultationCollectionService;
	@Autowired
	LearnReportService learnReportService;
    @Autowired
    ForecastService forecastService;
	@Autowired
	QuestionsCollectionService questionsCollectionService;
	/**
	 * 最新app版本地址
	 * 
	 * @author Guocg
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("/version")
	@ResponseBody
	public JsonResult version(Model model, @Valid UsersCondition vo,
			BindingResult br, HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		JSONObject object = new JSONObject();
		object.put("client", "1");
		object.put("version", "2.1.2");
		object.put("url", "http://114.55.227.224/yikaoshi.apk");
		object.put("comment", "更新内容：经过程序猿锅锅不停的加班，2.0终于上线啦！功能也更加强大咯！快快更新去体验吧~");
		return new JsonSuccessResult(session.getId(), object);
	}
	@RequestMapping("/about")
	@ResponseBody
	public JsonResult about(Model model,
			@Valid UsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("title", "");
			jsonObject.put("html", "");
			return new JsonSuccessResult(session.getId(), "获取成功",jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
	}
	@RequestMapping("/teacherCurrency")
	@ResponseBody
	public JsonResult teacherCurrency(Model model,
			@Valid UsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("title", "");
		String str=	"<!DOCTYPE html>"
				+" <html lang='en'>"
+" <head>"
+"   <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;' name='viewport' />"

+"    <meta charset='UTF-8'>"
+"  <title>教室币使用说明</title>"
+" </head>"
+" <body>"
+" <span><strong>一：设立目的</strong></span><br />&nbsp;&nbsp;&nbsp;&nbsp;1 记录学习时间（努力程度）和正确率（学习效果）<br />&nbsp;&nbsp;&nbsp;&nbsp;2 对努力程度高的同学和学习成绩优异者予以奖励<br />&nbsp;&nbsp;&nbsp;&nbsp;3 对本APP进行宣传的同学，予以奖励<br /><span><strong>二：获取规则</strong></span><br />&nbsp;&nbsp;&nbsp;&nbsp;1 分享应用奖励1个教师币。<br />&nbsp;&nbsp;&nbsp;&nbsp;2 完成练习奖励1个教师币。<br />&nbsp;&nbsp;&nbsp;&nbsp;3 评论题目奖励1个教师币。"
+" </body>"
+" </html>";
			jsonObject.put("html", str);
			return new JsonSuccessResult(session.getId(), "获取成功",jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
	}
	@RequestMapping("/myCollection")
	@ResponseBody
	@OAuthRequired
	public JsonResult myCollection(Model model,
			@Valid UsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());

		UsersVo usersVo = getUser(session);
		try {
			JSONObject jsonObject = new JSONObject();
			//学习报告
			LearnReportCondition learnReportCondition = new LearnReportCondition();
			learnReportCondition.setUserId(usersVo.getUserId());
			;
			jsonObject.put("learnReportNum", learnReportService
					.searchLearnReportNum(learnReportCondition));
			//咨询收藏
			ConsultationCollectionCondition collectionCondition = new ConsultationCollectionCondition();
			collectionCondition.setCollectionPeople(usersVo.getUserId());
			jsonObject.put("consultationNum", consultationCollectionService
					.searchConsultationCollectionNum(collectionCondition));
			//题库收藏
			QuestionsCollectionCondition questionsCollectionCondition = new QuestionsCollectionCondition();
			questionsCollectionCondition.setCollectionPeople(usersVo
					.getUserId());
			jsonObject
					.put("questionsNum",
							questionsCollectionService
									.searchQuestionsCollectionNum(questionsCollectionCondition));
			//题库数
			List<QuestionsCollectionVo> list = new ArrayList<QuestionsCollectionVo>();
			list = questionsCollectionService
					.findQuestionsCollectionPage(questionsCollectionCondition);
			QuestionsCollectionVo questionsCollectionVo = null;
			String ids = "";
			for (int i = 0; i < list.size(); i++) {
				questionsCollectionVo = list.get(i);
				ids = ids + questionsCollectionVo.getQuestionsId() + ",";

			}
			jsonObject.put("questionsIds", ids);
			return new JsonSuccessResult(session.getId(), "获取成功",jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}

	}
	/**
	 * 修改省市区
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	@OAuthRequired
	public JsonResult edit(Model model,
			@Valid UsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());

		UsersVo usersVo = getUser(session);
		try {
			UsersDetailsVo webappsUserCertificateVo = new UsersDetailsVo();
			//报告学科
			webappsUserCertificateVo.setUserId(usersVo.getUserId());
			webappsUserCertificateVo.setSubjectId(condition.getSubjectId());
			//教育综合
			webappsUserCertificateVo.setEducationId(condition.getEducationId());
			//省市区
			webappsUserCertificateVo.setAreaId(condition.getAreaId());
			webappsUserCertificateVo.setProvinceId(condition.getProvinceId());
			webappsUserCertificateVo.setCityId(condition.getCityId());
			usersDetailsService.updateSelective(webappsUserCertificateVo);
			return new JsonSuccessResult(session.getId(), "提交成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}

	}
	/**
	 * 修改省市区
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/editlocation")
	@ResponseBody
	@OAuthRequired
	public JsonResult editlocation(Model model,
			@Valid UsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());

		UsersVo usersVo = getUser(session);
		try {
			UsersDetailsVo webappsUserCertificateVo = new UsersDetailsVo();
			webappsUserCertificateVo.setUserId(usersVo.getUserId());
			webappsUserCertificateVo.setAreaId(condition.getAreaId());
			webappsUserCertificateVo.setProvinceId(condition.getProvinceId());
			webappsUserCertificateVo.setCityId(condition.getCityId());
			usersDetailsService.updateSelective(webappsUserCertificateVo);
			return new JsonSuccessResult(session.getId(), "提交成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}

	}

	/**
	 * 修改教育
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/editsubject")
	@ResponseBody
	@OAuthRequired
	public JsonResult editsubject(Model model, @Valid UsersCondition condition,
			BindingResult br, HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());

		UsersVo usersVo = getUser(session);
		try {
			UsersDetailsVo webappsUserCertificateVo = new UsersDetailsVo();
			webappsUserCertificateVo.setUserId(usersVo.getUserId());
			webappsUserCertificateVo.setSubjectId(condition.getSubjectId());
			usersDetailsService.updateSelective(webappsUserCertificateVo);
			return new JsonSuccessResult(session.getId(), "提交成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}

	}

	/**
	 * 修改学段
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/editEducation")
	@ResponseBody
	@OAuthRequired
	public JsonResult editEducation(Model model,
			@Valid UsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());

		UsersVo usersVo = getUser(session);
		try {
			UsersDetailsVo webappsUserCertificateVo = new UsersDetailsVo();
			webappsUserCertificateVo.setUserId(usersVo.getUserId());
			webappsUserCertificateVo.setEducationId(condition.getEducationId());
			usersDetailsService.updateSelective(webappsUserCertificateVo);
			return new JsonSuccessResult(session.getId(), "提交成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}

	}

	/**
	 * 修改名字
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/editName")
	@ResponseBody
	@OAuthRequired
	public JsonResult editName(Model model, @Valid UsersCondition condition,
			BindingResult br, HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		UsersVo usersVo = getUser(session);
		try {
			UsersDetailsVo webappsUserCertificateVo = new UsersDetailsVo();
			webappsUserCertificateVo.setUserId(usersVo.getUserId());
			webappsUserCertificateVo.setRealName(condition.getName());
			usersDetailsService.updateSelective(webappsUserCertificateVo);
			return new JsonSuccessResult(session.getId(), "提交成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}

	}

	/**
	 * 修改性别
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/editGender")
	@ResponseBody
	@OAuthRequired
	public JsonResult editGender(Model model, @Valid UsersCondition condition,
			BindingResult br, HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		UsersVo usersVo = getUser(session);
		try {
			UsersDetailsVo webappsUserCertificateVo = new UsersDetailsVo();
			webappsUserCertificateVo.setUserId(usersVo.getUserId());
			webappsUserCertificateVo.setGender(condition.getGender());
			usersDetailsService.updateSelective(webappsUserCertificateVo);
			return new JsonSuccessResult(session.getId(), "提交成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}

	}

	/**
	 * 个人中心
	 */
	@RequestMapping("/personal")
	@ResponseBody
	@OAuthRequired
	public JsonResult personal(Model model, LoginUsersCondition vo,
			BindingResult br, HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		try {
			UsersVo usersVo = getUser(session);

			UsersDetailsCondition usersDetailsCondition = new UsersDetailsCondition();
			usersDetailsCondition.setUserId(usersVo.getUserId());
			List<UsersDetailsVo> userList = usersDetailsService
					.findUsersDetailsPage(usersDetailsCondition);
			UsersDetailsVo usersDetailsVo = userList.get(0);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("mobilePhone", usersVo.getMobilePhone());
			if (usersDetailsVo.getFacePath() != null) {
				jsonObject.put("facePath", "http://" + bucketName + "."
						+ img_endpoint + "/" + usersDetailsVo.getFacePath());
			} else {
				jsonObject.put("facePath", "");
			}
			if (usersDetailsVo.getRealName() != null) {
				jsonObject.put("name", usersDetailsVo.getRealName());
			} else {
				jsonObject.put("name", "");
			}
			seetingJsonObject(jsonObject, "gender", usersDetailsVo.getGender());
			seetingJsonObject(jsonObject, "educationId",
					usersDetailsVo.getEducationId());
			EducationVo e = educationService.findById(usersDetailsVo
					.getEducationId());
			if (e != null && usersDetailsVo.getEducationId() != null
					&& usersDetailsVo.getEducationId() != 0) {
				seetingJsonObject(jsonObject, "education", e.getName());
			} else {
				seetingJsonObject(jsonObject, "education", "");
			}
			seetingJsonObject(jsonObject, "subjectId",
					usersDetailsVo.getSubjectId());
			SubjectVo s = subjectService
					.findById(usersDetailsVo.getSubjectId());
			if (s != null && usersDetailsVo.getSubjectId() != null
					&& usersDetailsVo.getSubjectId() != 0) {
				seetingJsonObject(jsonObject, "subject", s.getName());
			} else {
				seetingJsonObject(jsonObject, "subject", "");
			}

	
			 
			seetingJsonObject(jsonObject, "provinceId",
					usersDetailsVo.getProvinceId());
			seetingJsonObject(jsonObject, "cityId", usersDetailsVo.getCityId());
			seetingJsonObject(jsonObject, "areaId", usersDetailsVo.getAreaId());
			seetingJsonObject(jsonObject, "regTime",
					usersDetailsVo.getRegTime());

			RegionsCondition item = new RegionsCondition();
			List<RegionsVo> origins;
			RegionsVo webappsRegionsVo;
			String itemName = "";
			if (usersDetailsVo.getProvinceId() != null
					&& usersDetailsVo.getProvinceId() != 0) {
				// 获得省
				item.setItemId(usersDetailsVo.getProvinceId());
				item.setAreaId(0);
				item.setCityId(0);
				origins = regionsService.findRegionsPage(item);
				webappsRegionsVo = origins.get(0);
				itemName = webappsRegionsVo.getItemName();
				jsonObject.put("province", itemName);
			} else {
				jsonObject.put("province", itemName);
			}
			jsonObject.put("city", "统考");
//			if (usersDetailsVo.getCityId() != null
//					&& usersDetailsVo.getCityId() != 0) {
//				// 获得市
//				item.setProvinceId(usersDetailsVo.getProvinceId());
//				item.setItemId(null);
//				item.setCityId(usersDetailsVo.getCityId());
//				item.setAreaId(0);
//				origins = regionsService.findRegionsPage(item);
//				webappsRegionsVo = origins.get(0);
//				itemName = itemName + webappsRegionsVo.getItemName();
//				jsonObject.put("city", itemName);
//			} else {
//				jsonObject.put("city", "");
//			}
//
//			// 获取区
//			if (usersDetailsVo.getAreaId() != null
//					&& usersDetailsVo.getAreaId() != 0) {
//				item.setProvinceId(usersDetailsVo.getProvinceId());
//				item.setItemId(null);
//				item.setCityId(usersDetailsVo.getCityId());
//				item.setAreaId(usersDetailsVo.getAreaId());
//				origins = regionsService.findRegionsPage(item);
//				webappsRegionsVo = origins.get(0);
//				itemName = itemName + webappsRegionsVo.getItemName();
//				jsonObject.put("area", itemName);
//			} else {
//				jsonObject.put("area", "");
//			}
			// 教师币
			UserFinanceCondition condition = new UserFinanceCondition();
			condition.setUserId(usersVo.getUserId());
			List<UserFinanceVo> userFinanceVos = userFinanceService
					.findUserFinancePage(condition);
			if (!userFinanceVos.isEmpty()) {
				jsonObject.put("remaining", userFinanceVos.get(0)
						.getRemaining());
			} else {
				jsonObject.put("remaining", "0");
			}

			return new JsonSuccessResult(session.getId(), "成功", jsonObject);

		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
	}

	/**
	 * 登陆
	 * 
	 * @param model
	 * @param vo
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/login")
	@ResponseBody
	public JsonResult login(Model model, @Valid LoginUsersCondition vo,
			BindingResult br, HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		try {
			UsersCondition usersCondition = new UsersCondition();
			usersCondition.setPassword(DigestUtils.md5Hex(vo.getPassword()
					.getBytes("utf-8")));
			usersCondition.setStatus(1);
			usersCondition.setMobilePhone(vo.getMobilePhone());
			List<UsersVo> list = usersService.findUsersPage(usersCondition);
			if (!list.isEmpty()) {
				session.setAttribute(Consts.LOGIN_USER, list.get(0));// 同时登录
				JSONObject object = new JSONObject();
				object.put("user_id", list.get(0).getId());
				return new JsonSuccessResult(session.getId(), "登录成功", object);
			} else {
				return new JsonFailResult(session.getId(), "手机号或密码错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new JsonFailResult(session.getId(), 1, "后台报错",
					e.getMessage());
		}
	}

	@RequestMapping("/islogin")
	@ResponseBody
	public JsonResult islogin(Model model, @Valid LoginUsersCondition vo,
			BindingResult br, HttpSession session) {
		System.out.println("islogin----------------------------未登录");
		return new JsonFailResult(session.getId(), 2, "未登录");
	}

	@RequestMapping("/sendVerify")
	@ResponseBody
	public JsonResult sendVerify(Model model, @Valid MyCarNumCondition carNum,
			BindingResult br, HttpSession session) {

		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		String phoneNum1 = "", carNum1 = "";
		Object obj1 = null;
		if (carNum.getType().equals("phone")) {
			if (!Pattern.matches("^[1][34578][0-9]{9}$", carNum.getPhoneNum()))
				return new JsonFailResult(session.getId(), "phoneNum格式错误");
			phoneNum1 = carNum.getPhoneNum();
			obj1 = sendCodeMap.get(phoneNum1);
		}
		if (obj1 != null) {
			if ((DateUtils.addSeconds((Date) obj1, SECOND_TIME)
					.after(new Date())))
				return new JsonFailResult(session.getId(), 2, "发送过频");
		}

		String ran = RandomUtil.randomFor6();
		boolean re;
		JSONObject js = new JSONObject();
		if (carNum.isDebug())
			re = true;
		else {

			try {
				js = SMS.sendVerifyCodes(carNum.getPhoneNum(), ran);
			} catch (ApiException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return new JsonFailResult(session.getId(), "对不起，您的短信发送限制");
			}
			if (js != null) {
				re = true;
			} else {
				re = false;
				return new JsonFailResult(session.getId());
			}
		}

		if (!re)
			return new JsonFailResult(session.getId());
		else {
			sendCodeMap.put(carNum1, new Date());
			if (carNum.isDebug())
				js.put("BizId", "1111");
			return new JsonSuccessResult(session.getId(), js);
		}
	}

	/**
	 * 注册
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/registers")
	@ResponseBody
	public JsonResult registers(Model model,
			@Valid RegistersUsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		boolean isDebug = true;
		if (condition.getDeBug() != null && condition.getDeBug() == 1) {
			isDebug = false;
		}
		if (isDebug
				&& !SMS.SelectVerifyCode(condition.getCodeId(),
						condition.getMobilePhone(),
						Integer.valueOf(condition.getCode()))) {
			return new JsonFailResult(session.getId(), 2, "验证码失效，请重新获取");
		}
		UsersCondition userAccountCondition = new UsersCondition();
		userAccountCondition.setMobilePhone(condition.getMobilePhone());
		List<UsersVo> userAccountVos = usersService
				.findUsersPage(userAccountCondition);
		if (!userAccountVos.isEmpty()) {
			return new JsonFailResult(session.getId(), 2, "手机号已注册过,不可重复注册");
		}
		try {
			UsersVo acc = new UsersVo();
			acc.setMobilePhone(condition.getMobilePhone());
			acc.setAccountId(CreateMD5.getMd5(System.currentTimeMillis()
					+ condition.getMobilePhone()));
			acc.setPassword(DigestUtils.md5Hex((condition.getPassword()
					.getBytes("utf-8"))));
			acc.setStatus(1);
			acc.setAccountRole(1);
			Integer nid = usersService.merge(acc);
			if (nid == null) {
				return new JsonFailResult(session.getId(), -1, "后台报错");
			}
			UsersVo vo1 = usersService.findById(nid);

			UsersDetailsVo data = new UsersDetailsVo();
			data.setUserId(vo1.getUserId());
			data.setGender(1);
			data.setRegTime((int) (new Date().getTime() / 1000));
			data.setEducationId(condition.getEducationId());
			data.setSubjectId(condition.getSubjectId());
			nid = usersDetailsService.merge(data);
			if (nid == null) {
				return new JsonFailResult(session.getId(), -1, "后台报错");
			}
			// session.setAttribute(Consts.LOGIN_USER, vo1);// 同时登录
			// session.setAttribute(Consts.LOGIN_PHONE,
			// list.get(0).getMobilePhone());// 同时登录首页查询
			JSONObject object = new JSONObject();
			return new JsonSuccessResult(session.getId(), object);
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof DuplicateKeyException) {
				return new JsonFailResult(session.getId(), 2, "手机号已注册过,不可重复注册");
			}
			return new JsonFailResult(session.getId(), -1, "后台报错",
					e.getMessage());
		}
	}

	@RequestMapping("/users")
	@ResponseBody
	public JsonResult users(Model model, UsersCondition vo, BindingResult br,
			HttpSession session) {

		List<UsersVo> list = new ArrayList<UsersVo>();
		list = usersService.findUsersPage(vo);

		return new JsonSuccessResult(session.getId(), list);
	}

	@RequestMapping("/usersAdd")
	@ResponseBody
	public JsonResult usersAdd(Model model, UsersCondition vo,
			BindingResult br, HttpSession session) {
		UsersVo users = new UsersVo();
		usersService.insert(users);
		return new JsonSuccessResult(session.getId(), new Array());
	}

	@RequestMapping("/usersEdit")
	public JsonResult usersEdit(Model model, UsersCondition vo,
			BindingResult br, HttpSession session) {

		UsersVo users = new UsersVo();

		usersService.updateSelective(users);

		return new JsonSuccessResult(session.getId(), new Array());
	}

	/**
	 * 修改密码
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/editPassword")
	@ResponseBody
	@OAuthRequired
	public JsonResult editPassword(Model model,
			@Valid EditPasswordUsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());

		if (!condition.getPassword().equals(condition.getPasswordNew())) {
			return new JsonFailResult(session.getId(), 2, "新密码和旧密码不能一样");
		}
		boolean isDebug = true;
		if (condition.getDeBug() != null && condition.getDeBug() == 1) {
			isDebug = false;
		}
		if (isDebug
				&& !SMS.SelectVerifyCode(condition.getCodeId(),
						condition.getMobilePhone(),
						Integer.valueOf(condition.getCode()))) {
			return new JsonFailResult(session.getId(), 2, "验证码失效，请重新获取");
		}

		UsersCondition cvo = new UsersCondition();
		cvo.setMobilePhone(condition.getMobilePhone());

		List<UsersVo> list = usersService.findUsersPage(cvo);
		if (list.isEmpty())
			return new JsonFailResult(session.getId(), 1, "手机号未注册");
		UsersVo vo1 = new UsersVo();
		try {
			vo1.setPassword(DigestUtils.md5Hex(condition.getPasswordNew()
					.getBytes("utf-8")));
			vo1.setUserId(list.get(0).getUserId());
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		usersService.updateSelective(vo1);
		return new JsonSuccessResult(session.getId(), "成功");
	}

	/**
	 * 忘记密码
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/forgetPassword")
	@ResponseBody
	public JsonResult forgetPassword(Model model,
			@Valid EditPasswordUsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());
		// if (!checkLoginUser(condition.getMobilePhone(), session))
		// return new JsonFailResult(session.getId(), 2, "未登录");
		// UsersVo user = (UsersVo) session
		// .getAttribute(Consts.LOGIN_USER);
		// HttpSession session2 = MySessionContext.getSession(user.getUserId());
		// if (session2==null||!session.getId().equals(session2.getId())) {
		// log.info("已被踢掉:"+session.getId()+","+user.getId());
		// return new JsonFailResult(session.getId(), 2, "未登录");
		// }
		if (!condition.getPassword().equals(condition.getPasswordNew())) {
			return new JsonFailResult(session.getId(), 2, "两次输入密码不一样");
		}
		boolean isDebug = true;
		if (condition.getDeBug() != null && condition.getDeBug() == 1) {
			isDebug = false;
		}
		if (isDebug
				&& !SMS.SelectVerifyCode(condition.getCodeId(),
						condition.getMobilePhone(),
						Integer.valueOf(condition.getCode()))) {
			return new JsonFailResult(session.getId(), 2, "验证码失效，请重新获取");
		}

		UsersCondition cvo = new UsersCondition();
		cvo.setMobilePhone(condition.getMobilePhone());

		List<UsersVo> list = usersService.findUsersPage(cvo);
		if (list.isEmpty())
			return new JsonFailResult(session.getId(), 1, "手机号未注册");
		UsersVo vo1 = new UsersVo();
		try {
			vo1.setPassword(DigestUtils.md5Hex(condition.getPasswordNew()
					.getBytes("utf-8")));
			vo1.setUserId(list.get(0).getUserId());
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		usersService.updateSelective(vo1);
		return new JsonSuccessResult(session.getId(), "成功");
	}

	/**
	 * 修改投降
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/editPhoto")
	@ResponseBody
	@OAuthRequired
	public JsonResult editPhoto(Model model, @Valid UsersCondition condition,
			BindingResult br, HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());

		MultipartFile[] files = condition.getFile();
		if (files == null || files.length == 0) {
			return new JsonFailResult(session.getId(), "失败");
		}
		try {
			UsersVo usersVo = getUser(session);
			String url = uploadPic(files[0]);
			// byte[] bytes = files[i].getBytes();
			// File file2 = new File("/home/linwen/1/"+i+".jpg");
			// FileCopyUtils.copy(bytes, file2);
			UsersDetailsVo webappsUserCertificateVo = new UsersDetailsVo();
			webappsUserCertificateVo.setUserId(usersVo.getUserId());

			webappsUserCertificateVo.setFacePath(url);
			usersDetailsService.updateSelective(webappsUserCertificateVo);
			return new JsonSuccessResult(session.getId(), "提交成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new JsonFailResult(session.getId(), "失败");
		}
	}

	/**
	 * 修改手机号码1
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/editPhone")
	@ResponseBody
	@OAuthRequired
	public JsonResult editPhone(Model model,
			@Valid EditPhoneUsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());

		Object obj = session.getAttribute(Consts.LOGIN_USER);
		UsersVo userAccountVo = (UsersVo) obj;
		if (!userAccountVo.getMobilePhone().equals(condition.getMobilePhone())) {
			return new JsonFailResult(session.getId(), 1, "手机号码有误");
		}
		boolean isDebug = true;
		if (condition.getDeBug() != null && condition.getDeBug() == 1) {
			isDebug = false;
		}

		if (isDebug
				&& !SMS.SelectVerifyCode(condition.getCodeId(),
						condition.getMobilePhone(),
						Integer.valueOf(condition.getCode()))) {
			return new JsonFailResult(session.getId(), 2, "验证码失效，请重新获取");
		}
		return new JsonSuccessResult(session.getId(), "成功");

	}

	/**
	 * 修改手机号码2
	 * 
	 * @param model
	 * @param condition
	 * @param br
	 * @param session
	 * @return
	 */
	@RequestMapping("/editPhoneNew")
	@ResponseBody
	public JsonResult editPhoneNew(Model model,
			@Valid EditPhone2UsersCondition condition, BindingResult br,
			HttpSession session) {
		if (br.hasErrors())
			return new JsonFailResult(session.getId(), br.getAllErrors().get(0)
					.getDefaultMessage());

		if (condition.getMobilePhone().equals(condition.getMobilePhoneNew())) {
			return new JsonFailResult(session.getId(), 1, "新手机号码和旧手机号码不能相同");
		}

		try {
			Object obj = session.getAttribute(Consts.LOGIN_USER);
			UsersVo userAccountVo = (UsersVo) obj;
			if (!userAccountVo.getMobilePhone().equals(
					condition.getMobilePhone())) {
				return new JsonFailResult(session.getId(), 1, "手机号码有误");
			}
			userAccountVo.setMobilePhone(condition.getMobilePhoneNew());
			userAccountVo.setUserId(userAccountVo.getUserId());
			usersService.updateSelective(userAccountVo);
			UsersVo vos = usersService.findById(userAccountVo.getId());
			session.setAttribute(Consts.LOGIN_USER, vos);// 同时登录
			return new JsonSuccessResult(session.getId(), "提交成功");
		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof DuplicateKeyException) {
				return new JsonFailResult(session.getId(), 1, "手机号已注册过,不可重复注册");
			}
			return new JsonFailResult(session.getId(), -1, "后台报错",
					e.getMessage());
		}
	}

	/**
	 * 上传图片
	 * 
	 * @author Guocg
	 * @param file
	 * @return
	 * @throws Exception
	 */
	private String uploadPic(MultipartFile file) throws Exception {

		// byte[] bytes = file.getBytes();
		// File file2 = new File("d:/1/my.jpg");
		// FileCopyUtils.copy(bytes, file2);

		return UploadUtil.upload(file);
	}
}
